//
//  MYRegisterViewController.m
//  投融保
//
//  Created by 523 on 13-12-17.
//  Copyright (c) 2013年 木叶科技. All rights reserved.
//

#import "MYRegisterViewController.h"
#import "MYCustomTextField.h"

#import "MYVerifyEmailViewController.h"
#import "MYWebService.h"


@interface MYRegisterViewController ()

@end

@implementation MYRegisterViewController
{
    int Y_;
}

NSString *strMD5UserBaseId;
NSString *registerName;
NSString *realName;
NSString *idNum;
NSString *mail;

extern NSString *key;
int sex=1;



@synthesize bgScrollView;
@synthesize arrText;

@synthesize btnProtocol;


int prewTag ;  //编辑上一个UITextField的TAG,
float prewMoveY; //编辑的时候移动的高度

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    SETBACKGROUND
    [self initView];
    
    //监视键盘位置变化
    //    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(adaptKeyboardLocation:) name:UIKeyboardWillShowNotification object:Nil];
    
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void)initView
{
    Y_=0;
    if (IOS_VERSION>=7.0) {
        Y_=20;
    }
    
    //bgScrollView手势
    UITapGestureRecognizer *gesture=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewEndEditing)];
    
    self.bgScrollView=[UIScrollView new];
    [self.bgScrollView setShowsVerticalScrollIndicator:NO];
    [self.bgScrollView setFrame:CGRectMake(0, Y_, SCREEN_WIDTH,SCREEN_HEIGHT-Y_)];
    int scroll_y=150;
    if (SCREEN_HEIGHT>480) {
        scroll_y=50;
    }
    [self.bgScrollView setContentSize:CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT-Y_+scroll_y)];
    [self.bgScrollView setScrollEnabled:YES];
    [self.bgScrollView addGestureRecognizer:gesture];
    
    [self.view addSubview:bgScrollView];
    
    
    UIView *titleView=[[UIView alloc] initWithFrame:CGRectMake(0, Y_, SCREEN_WIDTH, 105)];
    [titleView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"titile_bg"]]];
    [self.view addSubview:titleView];
    
    UILabel *lblTitle=[[UILabel alloc] initWithFrame:CGRectMake(250, 15, 268, 66)];
    [lblTitle setText:@"注册"];
    [lblTitle setTextColor:[UIColor whiteColor]];
    [lblTitle setFont:[UIFont boldSystemFontOfSize:40]];
    lblTitle.textAlignment=NSTextAlignmentCenter;
    lblTitle.backgroundColor=[UIColor clearColor];
    [titleView addSubview:lblTitle];
    
    
    UIButton *btnReturn=[UIButton new];
    [btnReturn setFrame:CGRectMake(0, 0, 105, 105)];
    [btnReturn setImage:[UIImage imageNamed:@"return_icon"] forState:UIControlStateNormal];
    [btnReturn.titleLabel setFont:[UIFont systemFontOfSize:11]];
    [btnReturn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnReturn addTarget:self action:@selector(btnReturnClick) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview: btnReturn];
    
    float point_x=24;
    float point_y=145+Y_;
    float width=721;
    float height=104;
    
    self.arrText=[NSMutableArray new];
    NSArray *arrPlaceholder=[[NSArray alloc] initWithObjects:@"请输入您的账户名",@"请输入您的真实名", @"电子邮件",@"推荐人编号(选填)",nil];
    for (int i=0; i<=3; i++) {
        MYCustomTextField *text=[[MYCustomTextField alloc] initWithFrame:CGRectMake(point_x, point_y, width, height)];
        [text setPlaceholder:[arrPlaceholder objectAtIndex:i]];
        [text setAutocorrectionType:UITextAutocorrectionTypeNo];
        text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        [text setBackground:[UIImage imageNamed:@"textfild_bg"]];
        text.tag=10050+i;
        [text setFont:[UIFont systemFontOfSize:33.0]];
        [text addTarget:self action:@selector(closeKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
        text.delegate=self;
        [self.bgScrollView addSubview:text];
        [self.arrText addObject:text];
        point_y+=(height+20);
    }
    
    
    btnProtocol=[UIButton new];
    btnProtocol.frame=CGRectMake(point_x-2, point_y-13, 40, 40);
    btnProtocol.selected=YES;
    [btnProtocol setImage:[UIImage imageNamed:@"agreed_icon"] forState:UIControlStateSelected];
    [btnProtocol addTarget:self action:@selector(btnProtocolClick:) forControlEvents:UIControlEventTouchDown];
    [self.bgScrollView addSubview:btnProtocol];
    
    UILabel *lblProtocol=[UILabel new];
    [lblProtocol setFrame:CGRectMake(point_x+35, point_y-2, 400, 20)];
    lblProtocol.text=@"我已阅读并同意《用户协议》";
    lblProtocol.backgroundColor=[UIColor clearColor];
    lblProtocol.textColor=[UIColor darkGrayColor];
    lblProtocol.font=[UIFont systemFontOfSize:20];
    [self.bgScrollView addSubview:lblProtocol];
    point_y+=30;
    
    UIButton *btnRegister=[UIButton new];
    btnRegister.frame=CGRectMake(point_x, point_y+40, width, height);
    [btnRegister setBackgroundImage:[UIImage imageNamed:@"login_bg"] forState:UIControlStateNormal];
    [btnRegister setTitle:@"立即注册" forState:UIControlStateNormal];
    [btnRegister.titleLabel setFont:[UIFont systemFontOfSize:40]];
    [btnRegister addTarget:self action:@selector(btnNextStepClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.bgScrollView addSubview:btnRegister];
    
}

//立即注册事件
- (IBAction)btnNextStepClick:(UIButton *)sender
{
    
    if (btnProtocol.selected) {   //判断是否选择同意协议
        
        //得到页面每个text 中的数据
        NSMutableArray *arrStr = [NSMutableArray new];
        for(int i = 0; i <= 3; i++)
        {
            NSString *strText=((UITextField *)[self.view viewWithTag:10050+i]).text;
            if (i==3&&strText==nil) {
                strText=@" ";
            }
            [arrStr addObject:strText];
        }
        
        //++++++++++++++++
        //用户名重复判断
        //        NSString *strAppValidationUserNameService=@"service=appValidationUserNameService&userName=yudoudou";
        
        //+++++++++++++++
        
        //        NSString *strRegister = @"service=register&userName=jingjing&realName=晶晶&mail=masakap@gmail.com&certNo=50023319881029031&gender=1";
        //拼接待加密字符串
       
        NSString *strRegister;
        if ([[arrStr objectAtIndex:3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length>0) {
            strRegister=[NSString stringWithFormat:@"service=register&userName=%@&realName=%@&mail=%@&referees=%@",arrStr[0],arrStr[1],arrStr[2],arrStr[3]];
        }else
        {
            strRegister=[NSString stringWithFormat:@"service=register&userName=%@&realName=%@&mail=%@",arrStr[0],arrStr[1],arrStr[2]];
        }
    
        self.registerService=[MYWebService new];
        if (!mbHud) {
            mbHud = [[MBProgressHUD alloc] initWithView:self.view];
        }
        mbHud.labelText = @"正在加载";
        [self.view addSubview:mbHud];
        mbHud.delegate = self;
        [mbHud showAnimated:YES whileExecutingBlock:^{
            //z菊花转动的时候 开始加载数据
            [self.registerService getDataSynWithKey:key encryptedString:strRegister appKey:nil];
        } completionBlock:^{
            //执行加载数据完成后的操作。
            NSDictionary *dict=[self.registerService.profileDataSyn valueForKey:@"result"];
            //             NSLog(@"=============%@",[dict valueForKey:@"code"]);
            if ([[dict valueForKey:@"code"] intValue] ==1){
                strMD5UserBaseId=[dict valueForKey:@"MD5UserBaseId"];
                registerName=((UITextField *)[self.arrText objectAtIndex:0]).text;
                mail=((UITextField *)[self.arrText objectAtIndex:2]).text;
                realName=((UITextField *)[self.arrText objectAtIndex:1]).text;
                [self presentViewController:[MYVerifyEmailViewController new] animated:NO completion:nil];
            }
        }];
    }else
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:@"您需要同意用户协议" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
    }
    
    
}

//返回前页按钮方法
- (void)btnReturnClick
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//协议选择
- (IBAction)btnProtocolClick:(UIButton *)sender
{
    if (sender.selected) {
        [sender setImage:[UIImage imageNamed:@"disagreed_icon"] forState:UIControlStateNormal];
        sender.selected=!sender.selected;
    }
    else
    {
        [sender setImage:[UIImage imageNamed:@"agreed_icon"] forState:UIControlStateSelected];
        sender.selected=!sender.selected;
    }
}

#pragma mark +++++++++键盘+++++++++++
/**
 开始编辑UITextField的方法
 */
-(void) textFieldDidBeginEditing:(UITextField *)textField
{
    
    CGRect textFrame =  textField.frame;
    float textY = textFrame.origin.y+textFrame.size.height;
    float bottomY = self.bgScrollView.frame.size.height-textY;
    if(bottomY>=260)  //判断当前的高度是否已经有216，如果超过了就不需要再移动主界面的View高度
    {
        prewTag = -1;
        return;
    }
    prewTag = textField.tag;
    float moveY;
    if (SCREEN_HEIGHT>480) {
        moveY = 260-bottomY;
    }else
    {
        moveY = 300-bottomY;
    }
    
    prewMoveY = moveY;
    [UIView animateWithDuration:0.25 animations:^{
        [self.bgScrollView setContentOffset:CGPointMake(0, prewMoveY) animated:YES];
    }];
    
}

/**
 结束编辑UITextField的方法，让原来的界面还原高度
 */
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    mbHud = [[MBProgressHUD alloc] initWithView:self.view];
    
    //正则表达式验证
    switch (textField.tag) {
        case 10050://账户名
        {
            NSRegularExpression *regular=[NSRegularExpression regularExpressionWithPattern:@"[^A-Za-z0-9_]" options:0 error:nil];
            NSTextCheckingResult *result = [regular firstMatchInString:textField.text options:0 range:NSMakeRange(0, textField.text.length)];
            if (result) {
                //                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"用户名为字母数字下划线组合" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                //                [alert show];
                mbHud.labelText=@"用户名为字母数字下划线组合";
                [mbHud setMode:MBProgressHUDModeText];
                [self.view addSubview:mbHud];
                [mbHud showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    [mbHud removeFromSuperview];
                    mbHud = nil;
                }];
                
                return;
            }
            
            NSString *strAppValidationUserNameService=[NSString stringWithFormat:@"service=appValidationUserNameService&userName=%@",textField.text];
            NSDictionary *dict =[[MYWebService new] getDataSynWithKey:key encryptedString:strAppValidationUserNameService appKey:nil];
            NSLog(@"%@",[dict valueForKey:@"code"]);
            if ([[dict valueForKey:@"code"] intValue] ==0&&textField.text.length>0) {
                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"用户名已存在" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                [alert show];
                return;
            }
            
            
            
        }
            break;
        case 10051://真实姓名
        {
            NSRegularExpression *regular=[NSRegularExpression regularExpressionWithPattern:@"[^x00-xff]" options:0 error:nil];
            NSTextCheckingResult *result = [regular firstMatchInString:textField.text options:0 range:NSMakeRange(0, textField.text.length)];
            if (!result) {
                //                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"请输入真实姓名" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                //                [alert show];
                mbHud.labelText=@"请输入真实姓名";
                [mbHud setMode:MBProgressHUDModeText];
                [self.view addSubview:mbHud];
                [mbHud showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    [mbHud removeFromSuperview];
                    mbHud = nil;
                }];
            }
        }
            break;
            //        case 10052://证件号
            //        {
            //            NSRegularExpression *regular=[NSRegularExpression regularExpressionWithPattern:@"^(\\d{14}|\\d{17})(\\d|[xX])$" options:0 error:nil];
            //            NSTextCheckingResult *result = [regular firstMatchInString:textField.text options:0 range:NSMakeRange(0, textField.text.length)];
            //            if (!result) {
            //                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"请输入正确身份证" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
            //                [alert show];
            //            }
            //        }
            //
            //            break;
        case 10052://邮件
        {
            NSRegularExpression *regular=[NSRegularExpression regularExpressionWithPattern:@"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" options:0 error:nil];
            NSTextCheckingResult *result = [regular firstMatchInString:textField.text options:0 range:NSMakeRange(0, textField.text.length)];
            if (!result) {
                //                UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"邮箱输入有误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                //                [alert show];
                mbHud.labelText=@"邮箱输入有误";
                [mbHud setMode:MBProgressHUDModeText];
                [self.view addSubview:mbHud];
                [mbHud showAnimated:YES whileExecutingBlock:^{
                    sleep(1);
                } completionBlock:^{
                    [mbHud removeFromSuperview];
                    mbHud = nil;
                }];
            }
        }
            break;
        case 10053://推荐人编号
        {
            if ([textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length>0) {
                NSRegularExpression *regular=[NSRegularExpression regularExpressionWithPattern:@"^((13[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$" options:0 error:nil];
                NSTextCheckingResult *result = [regular firstMatchInString:textField.text options:0 range:NSMakeRange(0, textField.text.length)];
                if (!result&&textField.text.length>0) {
                    //                    UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:@"推荐人编号输入有误" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
                    //                    [alert show];
                    mbHud.labelText=@"推荐人编号输入有误";
                    [mbHud setMode:MBProgressHUDModeText];
                    [self.view addSubview:mbHud];
                    [mbHud showAnimated:YES whileExecutingBlock:^{
                        sleep(1);
                    } completionBlock:^{
                        [mbHud removeFromSuperview];
                        mbHud = nil;
                    }];
                }
            }
            
        }
            break;
        default:
            break;
    }
    
    if(prewTag == -1) //当编辑的View不是需要移动的View
    {
        return;
    }
    float moveY ;
    
    if(prewTag == textField.tag) //当结束编辑的View的TAG是上次的就移动
    {   //还原界面
        moveY =  prewMoveY;
        [self.bgScrollView setContentOffset:CGPointMake(0, moveY)];
    }
    
    
    
    
}
////适应键盘高度
//-(void)adaptKeyboardLocation:(NSNotification *)notification
//{
//
//    //NSLog(@"键盘高度即将变化");
//    CGFloat keyBoardHeightDelta;
//    //获取信件
//    NSDictionary *info= notification.userInfo;
//    //NSLog(@"通知携带的信息:%@",info);
//
//    CGRect beginRect=[[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue];
//    CGRect endRect=[[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue];
//    //时间
//    CGFloat duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
////    keyBoardHeightDelta=beginRect.origin.y-endRect.origin.y;
////    if (self.LoginBtn.frame.origin.y+self.LoginBtn.frame.size.height+20>keyboardRect.origin.y)
////    {
////        [UIView animateWithDuration:duration animations:^{
//////            [self.view setCenter:CGPointMake(self.view.center.x, self.view.center.y-keyBoardHeightDelta)]; //高端方案
////            [self.bgScrollView setFrame:CGRectMake(self.view.frame.origin.x, keyboardRect.origin.y-self.LoginBtn.frame.origin.y-45, self.view.frame.size.width, self.view.frame.size.height)];
////        }];
////    }
//}

- (void)scrollViewEndEditing
{
    [self.bgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.bgScrollView endEditing:YES];
}

- (void)closeKeyboard:(UITextField *)sender
{
    [self.bgScrollView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.view endEditing:YES];
}


#pragma mark-   -----------状态栏底色------
- (UIStatusBarStyle)preferredStatusBarStyle
{
    [self.view setBackgroundColor:[UIColor blackColor]];
    return UIStatusBarStyleLightContent;
}
- (BOOL)prefersStatusBarHidden
{
    return NO;
}
@end
